<template>
	<div v-if="isUrl" :style="urlIconStyle" class="svg-icon icon"/>
	<svg v-else :style="iconStyle" class="svg-icon icon">
		<use :href="iconName"/>
	</svg>
</template>

<script lang="ts" setup>
import {computed, type CSSProperties} from 'vue'
import {isExternal} from '@/utils/commonUtil'

interface Props {
	name: string
	size?: import('csstype').Property.FontSize<string | number>
	color?: import('csstype').Property.Color
}

const props = withDefaults(defineProps<Props>(), {
	name: '',
	size: '14px',
	color: 'currentColor'
})

const _name = computed(() => props.name)
const _size = computed(() => Number.isSafeInteger(Number(props.size)) ? `${props.size}px` : String(props.size))
const iconName = computed(() => `#${props.name}`)
const isUrl = computed(() => isExternal(props.name))
const iconStyle = computed((): CSSProperties => {
	return {
		color: props.color,
		fontSize: _size.value
	}
})
const urlIconStyle = computed(() => {
	return {
		width: _size.value,
		height: _size.value,
		mask: `url(${_name.value}) no-repeat 50% 50%`,
		'-webkit-mask': `url(${_name.value}) no-repeat 50% 50%`
	}
})
</script>

<style lang="scss" scoped>
.svg-icon {
	fill: currentColor;
	height: 1em;
	overflow: hidden;
	width: 1em;
}
</style>
